﻿using ChoJuRating.View;
using ChongJu.Camera;
using ChongJu.GlobalInfo;
using ChongJu.ImageAnalyze;
using GalaSoft.MvvmLight.Threading;
using Microsoft.Practices.Prism.Commands;
using Public.Logger;
using Public.MvvmBase;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Media;
using System.Windows.Media.Media3D;

namespace ChoJu.Single.ViewModel
{
    public class GreyImageVM : PropertyChangedBase
    {
        private bool _isRun;
        private int _count;
        private int _countTemp;

        //UI实时显示图片的数据流
        private MemoryStream _stream = null;

        private string _imgDirPath;

        public GreyImageVM()
        {
            _isRun = false;
            BtnContent = "采集";
            _imgDirPath = Path.Combine(AppContext.BaseDirectory, "GreyImage");
            if(Directory.Exists(_imgDirPath) == false)
                Directory.CreateDirectory(_imgDirPath);

            ChongJu.Camera.Camera.Instance.ImageCallBackEvent += Instance_ImageCallBackEvent;

            BtnClickCommand = new DelegateCommand(BtnClickFunction);
        }


        public string BtnContent
        {
            get { return _btnContent; }
            set { _btnContent = value; OnPropertyChanged(() => BtnContent); }
        }
        private string _btnContent;

        public string ImgCount
        {
            get { return _imgCount; }
            set { _imgCount = value; OnPropertyChanged(() => ImgCount); }
        }
        private string _imgCount = "10";

        public double R
        {
            get { return _r; }
            set { _r = value; OnPropertyChanged(() => R); }
        }
        private double _r;

        public double G
        {
            get { return _g; }
            set { _g = value; OnPropertyChanged(() => G); }
        }
        private double _g;

        public double B
        {
            get { return _b; }
            set { _b = value; OnPropertyChanged(() => B); }
        }
        private double _b;

        /// <summary>
        /// 当前烟叶图片
        /// </summary>
        public object CurrentImage
        {
            get { return _currentImage; }
            set { _currentImage = value; OnPropertyChanged(() => CurrentImage); }
        }
        private object _currentImage;

        public DelegateCommand BtnClickCommand { get;  }

        private void BtnClickFunction()
        {
            if(_isRun == false)
            {
                var bol = int.TryParse(ImgCount, out _count);
                if (bol == false || _count < 1)
                {
                    CJMsgBox.ShowDialog("请设置正确的图片数量");
                    return;
                }

                BtnContent = "停止";
                _isRun = true;
                _countTemp = 0;

                //删除之前的所有图片
                var images = Directory.GetFiles(_imgDirPath);
                foreach(var image in images) 
                    File.Delete(image);

                Task.Run(() =>
                {
                    try
                    {
                        GlobalVar.CurrentRunType = ChongJu.ModelManager.RunTypeEnum.Verification;
                        for (int i = 0; i < _count; i++)
                        {
                            ChongJu.Camera.Camera.Instance.TakePicture();
                            Thread.Sleep(1000);
                        }
                    }
                    catch(Exception ex) { }
                    finally 
                    {
                        GlobalVar.CurrentRunType = ChongJu.ModelManager.RunTypeEnum.None;
                    }
                    
                });
            }
            else
            {
                BtnContent = "采集";
                _isRun = false;
            }
        }


        private void Instance_ImageCallBackEvent(Bitmap bitmap, DateTime time)
        {
            if (_isRun == false)
                return;

            _countTemp++;
            var file = Path.Combine(_imgDirPath, DateTime.Now.ToString("yyMMddHHmmssfff") + ".png");
            bitmap.Save(file);

            ViewImageUI(bitmap);

            if (_count == _countTemp)
            {
                BtnContent = "采集";
                _isRun = false;
                ParserRGB(_imgDirPath);
            }
        }

        private void ViewImageUI(Bitmap image)
        {
            try
            {
                if (_stream != null)
                    _stream.Dispose();

                _stream = new MemoryStream();
                var compress = new SaveImage().ImageCompress(image);
                if (compress == null)
                    return;

                compress.Save(_stream, ImageFormat.Png);
                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    try
                    {
                        if (_stream != null)
                            CurrentImage = (ImageSource)new ImageSourceConverter().ConvertFrom(_stream);

                        compress?.Dispose();
                        image?.Dispose();
                    }
                    catch (Exception ex)
                    {
                        Logger.Error("UI显示图片异常,内部调用", ex);
                    }
                });
            }
            catch (Exception ex)
            {
                Logger.Error("UI显示图片异常", ex);
            }
        }

        private void ParserRGB(string dirPath)
        {
            var dir = Marshal.StringToHGlobalAnsi(dirPath);

            double r_g = 0;
            double g_g = 0;
            double b_g = 0;
            int r_m = 0;
            int g_m = 0;
            int b_m = 0;
            int light = 0;
            int success = 0;
            AnalyzeService.Instance.CalibraLightCamera(dir,
                       80, 80, 80,
                       ref b_g, ref g_g, ref r_g,
                       ref light, ref b_m, ref g_m, ref r_m,
                       ref success);

            R = Math.Round(r_g, 2);
            G = Math.Round(g_g, 2);
            B = Math.Round(b_g, 2);
        }
    }
}
